package com.ww.springboot.boot.thread.study.base.other;

import com.ww.springboot.boot.thread.study.base.lock.LockDemo1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.IntConsumer;

/**
 * 描述：
 *
 * @author wanwei
 * @since 2021-11-05 14:52
 */
public class ZeroEvenOdd {


    static int n = 0;
    static Lock lock = new ReentrantLock();
    static Condition conditionA = lock.newCondition();
    static Condition conditionB = lock.newCondition();
    static Condition conditionC = lock.newCondition();
    static int max = 10;

    private static ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd();

    private static Thread threadA;
    private static Thread threadB;
    private static Thread threadC;

    public static void main(String[] args) throws InterruptedException {

        threadA = new Thread(() -> {
            try {
                zeroEvenOdd.zero();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        threadB = new Thread(() -> {
            try {
                zeroEvenOdd.odd();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        threadC = new Thread(() -> {
            try {
                zeroEvenOdd.even();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        threadB.start();
        threadC.start();
        Thread.sleep(10);
        threadA.start();
    }


    public void zero() throws InterruptedException {
        lock.lock();
        try {
            while (n < max) {
                if (n != 0) {
                    conditionA.await();
                } else {
                    n++;
                }
                System.out.println("zero-" + 0);
                if (n % 2 == 1) {
                    conditionB.signal();
                } else {
                    conditionC.signal();
                }
            }
        } finally {
            lock.unlock();
        }
    }

    public void even() throws InterruptedException {
        lock.lock();
        try {
            while (n < max) {
                conditionB.await();
                System.out.println("even-" + n++);
                conditionA.signal();
            }
        } finally {
            lock.unlock();
        }
    }

    public void odd() throws InterruptedException {
        lock.lock();
        try {
            while (n < max) {
                conditionC.await();
                System.out.println("odd -" + n++);
                conditionA.signal();
            }
        } finally {
            lock.unlock();
        }
    }
}
